package com.ruoyi.rulengine.listener;



import com.ruoyi.rulengine.domain.Rule;
import com.ruoyi.rulengine.domain.RuleCondition;
import com.ruoyi.rulengine.evaluator.RuleConditionEvaluator;
import com.ruoyi.rulengine.service.IAsyncRuleEngineService;
import com.ruoyi.rulengine.service.IRuleEngineService;
import jakarta.annotation.Resource;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import com.ruoyi.iotcommon.constant.RocketTopicConstant;
import com.ruoyi.iotcommon.domain.DeviceDataMessage;

import java.util.ArrayList;
import java.util.List;


/**
 * 设备上报数据监听器
 */
@Service
@RocketMQMessageListener( topic = RocketTopicConstant.DEVICE_DATA, consumerGroup = "iot-rulengine-device-data")
public class DeviceDataListener implements RocketMQListener<DeviceDataMessage>{

    @Resource
    private IAsyncRuleEngineService ruleEngineService;


    @Override
    public void onMessage(DeviceDataMessage deviceData) {
        // 从缓存查询设备规则，并执行规则引擎

        List<Rule> rules = new ArrayList<>();

        // 规则1：温度大于30且湿度小于50，触发发送通知和记录日志
        Rule rule1 = new Rule();
        rule1.setLogical("AND");
        rule1.setConditions(List.of(
               // new RuleCondition("temperature", ">", "30"),
               // new RuleCondition("humidity", "<", "50")
        ));
        rule1.setActions(List.of(
              //  new RuleCondition(),
              //  new RuleCondition()
        ));

        // 规则2：温度大于40或湿度小于30，触发发送通知
        Rule rule2 = new Rule();
        rule2.setLogical("OR");
        rule2.setConditions(List.of(
              //  new RuleCondition("temperature", ">", "40"),
              //  new RuleCondition("humidity", "<", "30")
        ));
        rule2.setActions(List.of(
                //new SendNotificationAction()
        ));

        rules.add(rule1);
        rules.add(rule2);

        // 执行规则引擎
        //ruleEngineService.evaluateRules(rules, deviceData);
        // 异步执行规则引擎，多条件异步同时判断，多动作，异步同时执行
        ruleEngineService.evaluateRulesAsync(rules, deviceData);
    }
    
}
